import { type Ref, ref, watch } from 'vue';
import { isArray, isUndefined } from 'lodash-es';
import type { QueryFunType, SetQueryFunType } from '../types/queryType';
import { setKeyString } from './utls';
import type { Fn } from '@vueuse/core';
import type { TreeNode } from 'element-plus/es/components/tree-v2/src/types';
import { ElMessage } from 'element-plus';

const dataAll = ref<TreeNode[]>([]);
const searchText = ref<string>();
const range = ref<string>();
const index = ref<number>(-1);
export function useQuery(
  ConfigQueryRegisterClose: Fn,
  setQuery: Function,
  gData: Ref<TreeNode[]>,
  setGData: Function,
) {
  const dataList = ref<TreeNode[]>([]);
  const letTopTwoState = ref<1 | 2 | 3>(1); // 1 正常  2查询全部 3归档单位查询
  watch(
    () => gData.value,
    (value) => {
      if (value) {
        dataList.value = gData.value;
      }
    },
    {
      immediate: true,
    },
  );
  function queryCheck(e: QueryFunType) {
    // console.log('eee', e)
    if (e.type == 'cancel') {
      searchText.value = '';
      index.value = -1;
      ConfigQueryRegisterClose();
    } else if (e.type == 'one') {
      oneFun(e);
    } else {
      // 调用后端接口
      searchText.value = e.searchText;
      dataAll.value = [];
      dataProcessing(dataList.value, e.range as 'all' | 'table' | 'folder');
      dataAll.value.map((e) => {
        e.children = [];
        return e;
      });
      // console.log('dataAll.value..........', dataAll.value)

      setGData(dataAll.value);
      letTopTwoState.value = 2;
      ConfigQueryRegisterClose();
      setQuery({ expandedKeys: [], selectedKeys: [], selectObj: undefined });
    }
  }

  async function oneFun(e: QueryFunType) {
    console.log('eeee', e);
    const query: SetQueryFunType = {
      expandedKeys: [],
      selectedKeys: [],
      selectObj: undefined,
    };

    if (e.searchText != searchText.value || range.value != e.range) {
      // console.log('query', query)

      setQuery({
        expandedKeys: [],
        selectedKeys: [],
        selectObj: undefined,
      });

      // 不同
      searchText.value = e.searchText;
      range.value = e.range;
      index.value = -1;
      dataAll.value = [];
      dataProcessing(dataList.value, e.range as 'all' | 'table' | 'folder');
      // console.log('aaaaaaaaaaaaa', dataAll.value)
    }
    if (!isArray(dataAll.value) || dataAll.value.length == 0) {
      return ElMessage.warning('暂无搜索内容');
    }
    if (e.direction == 'down' && dataAll.value.length - 1 == index.value) {
      return ElMessage.warning('暂无更多内容');
    }
    if (e.direction == 'up' && index.value == 0) {
      return ElMessage.warning('暂无更多内容');
    }
    if (e.direction == 'down') {
      index.value++;
    } else {
      if (index.value == -1) {
        return ElMessage.warning('暂无更多内容');
      } else {
        index.value--;
      }
    }
    const dataOne: any = dataAll.value[index.value];
    // console.log('dataOne.key', dataOne)

    const expandedKeys = expandTap(dataOne.key as string);
    query.expandedKeys = expandedKeys;
    query.selectedKeys = [dataOne.key as string];
    query.selectObj = dataOne;
    setQuery(query);
  }
  function setLetTopTwoState(num: 1 | 2 | 3) {
    letTopTwoState.value = num;
  }

  return {
    queryCheck,
    letTopTwoState,
    setLetTopTwoState,
  };
}

// 获取 展开keys
function expandTap(dataKey: string) {
  if (isUndefined(dataKey)) return [];
  const expandedKeys: string[] = [];
  const aa: string[] = dataKey.includes('-') ? dataKey.split('-') : [dataKey];
  for (let i = 0; i < aa.length; i++) {
    const data = setKeyString(aa, i);
    expandedKeys.push(data);
  }
  return expandedKeys;
}
// 数据处理
async function dataProcessing(data: TreeNode[] | any, range: 'all' | 'table' | 'folder') {
  // console.log('数据处理', range, data)

  for (let i = 0; i < data.length; i++) {
    const element = data[i];
    if (element.title.includes(searchText.value)) {
      if (range == 'all') {
        dataAll.value.push(element);
      } else if (range == 'folder') {
        // 文件夹
        if (element.type == 1) {
          dataAll.value.push(element);
        }
      } else if (range == 'table') {
        // 表格
        if (element.type != 1) {
          dataAll.value.push(element);
        }
      }
    }

    if (isArray(element.children) && element.children.length) {
      dataProcessing(element.children, range);
    }
  }
}
